<template>
  <div>
    <el-header>
      <Nav1></Nav1>
    </el-header>
    <el-container>


      <aside-bar :userid="this.userId" :articleid="this.articleId"
                 :islike="this.islike" :isStar="this.isStar"
                 :likeCount="this.count.likeCount" :starCount="this.count.starCount"
                 v-if="flag"
      ></aside-bar>
      <div class="container">
        <!--        文章内容-->
        <el-main>
          <el-card class="text">
            <h1 class="head">{{ article.title }}</h1>
            <div class="article-meta">{{ article.createTime }}&nbsp;{{ article.author }}</div>
            <div class="text-content">
              <div v-html="article.content">
              </div>
            </div>
          </el-card>

          <!--         评论编写区-->
          <el-card>
            <div class="vertical-container">
              <el-form label-width="160px">
                <div class="comment-item">评论&nbsp;{{ commentTopList.length }}:</div>
                <el-form-item label="请发表你的评论">
                  <el-input type="textarea" v-model="comment.content"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" @click="onComment" class="comment-onsubmit"
                             :disabled=" comment.content === ''"
                  >提交评论
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>

          <!--          显示一级评论-->
          <el-card>

            <el-card class="comment-card" shadow="never" style="border: none;"
                     v-for="(item,index) in commentTopList" :key="index">
                <div class="comment-username">
                  {{ item.username }}:
                </div>
                <div class="comment-content">
                  {{ item.content }}
                </div>
                <div class="comment-date">
                  {{ item.createTime }}
                </div>


                <!--              回复一级评论-->
                <div class="reply">
                  <el-button @click="isindex=index">回复</el-button>
                  <el-button type="danger"
                             @click="topcommentDelete(commentTopList[index].commentId,commentTopList[index].topCommentId)"
                             v-if="commentTopList[index].userId == userId">删除
                  </el-button>
                  <!--                <div>{{ commentTopList[index].userId }}</div>-->
                  <el-input type="textarea" v-if="isindex === index" v-model="commentReply.content"></el-input>
                  <el-button type="danger" @click="onCommentReply(item.topCommentId)" class="comment-onsubmit"
                             v-if="isindex === index"
                             :disabled=" commentReply.content === ''"
                  >提交回复
                  </el-button>

                </div>

                <!--              显示回复评论-->
                <div class="sub-comments">
                  <el-card v-for="(item2,index2) in commentReplyList[index]" :key="index2"
                           class="comment-card sub-comment"
                           shadow="never" style="border: none;">
                    <!--                  <div >-->
                    <!--                    {{item2.title}}:-->
                    <!--                  </div>-->
                    <div class="comment-username">
                      {{ item2.username }}
                    </div>
                    <div class="comment-content">
                      {{ item2.content }}
                    </div>
                    <div class="comment-date">
                      {{ item2.createTime }}
                    </div>
                    <el-button type="danger "
                               v-if="item2.userId == userId"
                               @click="commentreplyDelete(item2.commentId,item.commentReply[index2].replyCommentId)"
                    >删除
                    </el-button>
                  </el-card>
                </div>
            </el-card>

          </el-card>

        </el-main>

      </div>
    </el-container>
  </div>
</template>

<script >
import Nav1 from "@/components/nav/Nav1.vue";
import AsideBar from "@/components/Aside/AsideBar.vue";
import {
  articleInfo,
  commentList,
  commentTopDel,
  commentTopInsert,
  likeStatusCheck,
  starStatusCheck,
  commentTopContent, commentReplyInsert, commentReplyContent, commentReplyDel
} from "@/utils/api";
import {parseTime} from "../../../public/FormatTime";

export default {
  components: {
    Nav1,
    AsideBar,
  },
  data() {
    return {
      article: {},

      userId: 0,
      articleId: 0,

      likeStatusKey: {
        userId: 0,
        articleId: 0,

      },
      commentTop1: {
        topCommentId: 0,
        articleId: '',
        commentId: ''
      },
      islike: false,
      comment: {
        createTime: '',
        content: '',
        userId: 0
      },
      commentReply: {
        createTime: '',
        content: '',
        userId: 0,
      },
      commentReply1: {
        commentId: '',
        replyCommentId: 0,
      },
      flag: false,
      isreply: false,
      isindex: -1,

      starStatusKey: {
        userId: 0,
        articleId: 0
      },
      isStar: false,

      count: {
        likeCount: 0,
        starCount: 0
      },
      commentTop: [],
      commentReplyList: [],
      commentTopList: [],
      topLevelComment: {},
      commentBase: {}
      //     {
      //   username: '用户名',
      //   content: '这是一个顶级评论的内容',
      //   subComments: [
      //     {
      //       id: 1,
      //       username: '子评论用户',
      //       content: '这是一个子评论的内容',
      //     },
      //     // 可以添加更多子评论
      //   ],
      // },
    };
  },
  methods: {

    //获取文章内容（请求：传文章id）
    async ArticleInfo() {
      // 使用catch反向逻辑,避免过多逻辑嵌套

      const res = await articleInfo(this.$route.params.id).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');


      this.article = res.data;
      for (let k in this.article) {
        if (k === 'createTime')
          this.article[k] = parseTime(this.article[k])
      }
      // console.log(this.article)
      // alert(this.article.createTime)

    },


    // 查看是否点赞和收藏
    async likeStatuscheck() {
      // alert("???")
      // 使用catch反向逻辑,避免过多逻辑嵌套

      // 查看是否点赞
      const res = await likeStatusCheck(this.likeStatusKey).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');
      // alert(res.isLike)
      this.islike = res.isLike

      // 查看是否收藏
      const res2 = await starStatusCheck(this.starStatusKey).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res2, '请求成功');
      this.isStar = res2.isStar
      // alert(this.isStar)

      this.flag = true

    },

    // reply(index){
    //   this.isreply = true
    //   return index
    // },
    // 添加一级评论
    async onComment() {
      // alert("评论成功");

      let date = new Date()
      // alert(date.getTime()/1000)
      this.comment.createTime = date.getTime() / 1000

      //评论（请求：传文章id和comment）
      const res = await commentTopInsert(this.comment, this.articleId).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');
      location.reload()

    },

    // 获取一级评论和回复评论内容
    async CommentInfo() {
      // 使用catch反向逻辑,避免过多逻辑嵌套

      const res = await commentList(this.$route.params.id).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');

      // this.topLevelComment = res.data;
      //
      // console.log(this.topLevelComment)
      // alert(this.article.createTime)

      this.commentTop = res.data.commentTop
      for (let i = 0; i < this.commentTop.length; i++) {
        this.commentTop[i].commentReply = res.data.commentReply[i]
      }
      console.log('ccc')
      console.log(this.commentTop)


      // 根据commentTop的topCommentId获取评论内容
      for (let i = 0; i < this.commentTop.length; i++) {
        const res2 = await commentTopContent(this.commentTop[i].topCommentId).catch(err => {
          // 提示错误, 终止执行
          return console.error(err)
        })
        // console.log(res2, '请求成功');
        res2.data.commentBase.createTime = parseTime(res2.data.commentBase.createTime)
        res2.data.commentBase.topCommentId = res2.data.topCommentId
        res2.data.commentBase.commentReply = this.commentTop[i].commentReply
        this.commentTopList.push(res2.data.commentBase)
        // this.commentBase= res2.data.commentBase
      }
      console.log("bbb")
      console.log(this.commentTopList);


      // 获取回复评论内容
      for (let i = 0; i < this.commentTop.length; i++) {
        // 使用catch反向逻辑,避免过多逻辑嵌套
        const replyArr = []
        for (let j = 0; j < this.commentTop[i].commentReply.length; j++) {
          const res3 = await commentReplyContent(this.commentTop[i].commentReply[j].replyCommentId).catch(err => {
            // 提示错误, 终止执行
            return console.error(err)
          })
          // alert('aaa')
          // console.log(res3, '请求成功');
          // this.commentBase = res3.data.commentBase
          res3.data.commentBase.createTime = parseTime(res3.data.commentBase.createTime)
          replyArr.push(res3.data.commentBase)
          // this.commentTopList[i].commentReply[j].push(this.commentBase)

          console.log("???")
          console.log(this.commentTopList)
        }
        this.commentReplyList.push(replyArr)
        console.log("112233")
        console.log(this.commentReplyList)
      }


    },

    // 添加回复评论
    async onCommentReply(topCommentId) {

      let date = new Date()
      this.commentReply.createTime = date.getTime() / 1000
      // 使用catch反向逻辑,避免过多逻辑嵌套
      const res = await commentReplyInsert(this.commentReply, topCommentId).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');
      location.reload()

    },


    //顶级评论删除
    async topcommentDelete(commentId, topCommentId) {
      this.commentTop1.articleId = this.articleId
      this.commentTop1.commentId = commentId
      this.commentTop1.topCommentId = topCommentId
      const res = await commentTopDel(this.commentTop1, this.userId).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');
    },

    //回复评论删除
    async commentreplyDelete(commentId, replyCommentId) {
      alert('aaa')
      this.commentReply1.commentId = commentId
      this.commentReply1.replyCommentId = replyCommentId
      const res = await commentReplyDel(this.commentReply1, this.userId).catch(err => {
        // 提示错误, 终止执行
        return console.error(err)
      })
      console.log(res, '请求成功');
    }

  },
  created() {

    this.flag = false
    if (window.sessionStorage.getItem("userId")) {
      this.userId = sessionStorage.getItem("userId")
      // 发评论
      this.comment.userId = sessionStorage.getItem('userId')
      this.commentReply.userId = sessionStorage.getItem('userId')
      // 查看是否点赞
      this.likeStatusKey.userId = this.userId
      // 查看是否收藏
      this.starStatusKey.userId = this.userId
    } else
      this.userId = 0

    // console.log(this.$route.params.id)
    this.articleId = this.$route.params.id
    // alert(this.articleId)

    // 获取文章
    this.ArticleInfo()


    // 查看是否点赞
    this.likeStatusKey.articleId = this.$route.params.id

    // 查看是否收藏
    this.starStatusKey.articleId = this.$route.params.id
    this.likeStatuscheck()

    //获取评论信息(一级和二级)
    this.CommentInfo()
    this.CommentReplyInfo()


  },
};
</script>

<style >

.comment-card {
  margin: 10px;
  padding: 10px;

}
.comment-card .el-card__body{
  border: 2px solid #cccccc;
  border-radius: 4px;
}


.comment-username {
  font-size: 16px;
  font-family: "SimSun", Sans-serif;
  font-weight: bold;
}

.comment-content {
  padding: 10px;
  background-color: #f5f5f5;
}

.comment-date {
  font-family: Arial, sans-serif;
  font-size: 14px;
  color: #333;
  margin-left: 20px;

}

.sub-comment {
  margin-top: 10px;
  border-left: 3px solid #ccc;
  padding-left: 10px;
}

.vertical-container {
  display: flex; /* 使用Flex布局 */
  flex-direction: column; /* 垂直排列 */
  margin: 20px 160px;
//align-items: center;   /* 水平居中对齐 */
}

.comment-item {
  margin-bottom: 15px; /* 添加底部间距以确保换行 */
//background: #f04142; font-size: 30px; font-family: SimSun; font-weight: bold;
}

.comment-onsubmit {
  position: absolute;
  right: 1%;
}

.container {
  margin: 40px auto 0;
  padding: 10px 20px 50px 20px;
  min-width: 1300px;
  max-width: 1300px; /* 设置最大宽度 */
  box-sizing: border-box;
  flex-shrink: 0;
//display: flex; //justify-content: center; /* 水平居中 */ //align-items: center; /* 垂直居中  */
}

.text {
//border: #f8f8f8; padding-left: 160px; padding-right: 80px;

}

.head {
  font-size: 37px;
  font-weight: 600;
  line-height: 56px;
  color: #000;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中  */
}

.article-meta {
  margin: 16px 0 36px;
  font-size: 14px;
  line-height: 20px;
  color: #707070;
}

.text-content {
//border: 1px solid #ccc; padding: 0 10%; display: flex; justify-content: center; /* 水平居中 */ padding: 30px 10%; display: flex; justify-content: center; align-items: center;
  border: 2px solid #00000040;
  border-radius: 4px;
}
</style>
